package cn.agiledata.bank.barcodepayment.logic;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import cn.agiledata.bank.barcodepayment.exception.BarCodePayException;
import cn.agiledata.bank.common.util.DateUtil;
/**
 * 涓婃捣娴︿笢澶╃劧姘斿叕鍙告敹璐规潯褰㈢爜
 * 
 * @author 马贤波
 * 
 */
public class PuDongGasBarCode extends AbstractBarCode {
    /**
     * 鏉″舰鐮佸�鐨勯暱搴�
     */
    private static int CODE_SIZE = 24;

    public BigDecimal getAmount() {
        return getAmount(17, 23);
    }

    public Date getDate() {
        String ds = getValue().substring(11,15);
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        String dateValue = (year / 100) + ds;
        return DateUtil.string2Date(dateValue, "yyyyMM");
    }
    protected void validate(String barCodeValue) throws BarCodePayException {
        super.validate(barCodeValue);
        if (barCodeValue.length() != CODE_SIZE) {
            throw BarCodePayException.ERROR_BARCODE_LENGTH;
        }
        String b23 = barCodeValue.substring(0,23);
        String e1 = barCodeValue.substring(23,24);
        int lastNum = Integer.valueOf(e1).intValue();
        int sum = 0;
        for (int i = 1; i <= b23.length(); i++) {
            if (i % 2 == 1) { // 濂囨暟浣�
                sum += intOf(barCodeValue, i) * 3;
            } else { // 鍋舵暟浣�
                sum += intOf(barCodeValue, i);
            }
        }
        String s = String.valueOf(sum);
        s = s.substring(s.length()-1,s.length());
        int end = Integer.valueOf(s).intValue();
        if (end != 0) {
            if (10-end != lastNum) { // 涓綅鏁颁笉涓�
                throw BarCodePayException.ERROR_BARCODE;
            }
        }
        Date d = getDate();
        Calendar codeDate = Calendar.getInstance();
        codeDate.setTime(d);
        int codeYear = codeDate.get(Calendar.YEAR);
        Calendar now = Calendar.getInstance();
        int nowYear = now.get(Calendar.YEAR);
        if (codeYear > nowYear && codeYear < nowYear-1) {
            throw BarCodePayException.ERROR_BARCODE;
        }
    }
}
